package com.huangyi;

public class Main {
    public static void main(String[] args) {
        // 测试用例 - 两整数之和
        Solution solution1 = new Solution();
        System.out.println("两整数之和:");
        System.out.println("1 + 2 = " + solution1.getSum(1, 2)); // 3
        System.out.println("2 + 3 = " + solution1.getSum(2, 3)); // 5
        System.out.println("-1 + 1 = " + solution1.getSum(-1, 1)); // 0

        // 测试用例 - 只出现一次的数字II
        Solution2 solution2 = new Solution2();
        System.out.println("\n只出现一次的数字II:");
        int[] nums1 = {2, 2, 3, 2};
        System.out.println("[2,2,3,2]: " + solution2.singleNumber(nums1)); // 3
        int[] nums2 = {0, 1, 0, 1, 0, 1, 99};
        System.out.println("[0,1,0,1,0,1,99]: " + solution2.singleNumber(nums2)); // 99
    }

    // 两整数之和
    static class Solution {
        public int getSum(int a, int b) {
            while (b != 0) {
                int sum = a ^ b;       // 无进位和
                int carry = (a & b) << 1; // 进位
                a = sum;
                b = carry;
            }
            return a;
        }
    }

    // 只出现一次的数字II
    static class Solution2 {
        public int singleNumber(int[] nums) {
            int ret = 0;
            for (int i = 0; i < 32; i++) {
                int sum = 0;
                for (int num : nums) {
                    sum += (num >> i) & 1; // 统计第 i 位
                }
                if (sum % 3 != 0) {
                    ret |= (1 << i); // 恢复结果的第 i 位
                }
            }
            return ret;
        }
    }
}